import json
from json.decoder import JSONDecodeError

from selenium import webdriver
import time
import requests
from selenium.common.exceptions import NoSuchElementException, ElementNotInteractableException, \
    ElementClickInterceptedException, WebDriverException

from domain.Receipt import Receipt
from util import ReceiptTypeUtil
from util.ConfigParserImpl import ConfigParserImpl

"""
公司OA 出租车发票报销
"""

print('-------------------准备好,开始报销-----------------')

file = 'config/config.ini'
config = ConfigParserImpl()

config.read(file, encoding='utf-8')

# 获取所有section
sections = config.sections()

# 获取发票类型字典
receiptTypeMap = ReceiptTypeUtil.readConfig()

# 获取系统配置信息
systemInfo = config.items('system-info')
systemInfo = dict(systemInfo)

# 获取公共信息
publicInfo = config.items('public-info')
# 可以通过dict方法转换为字典
publicInfo = dict(publicInfo)

# 获取用户信息
userInfo = config.items('user-info')
userInfo = dict(userInfo)

browser = webdriver.Chrome(systemInfo['chromeDriverPath'])
browser.maximize_window()
browser.get(publicInfo['companyUrl'])
print('打开门户系统')

browser.find_element_by_name('userName').click()
time.sleep(0.3)

# 输入用户信息
userName = browser.find_element_by_name('userName')
userName.send_keys(userInfo['employeeAccount'])
time.sleep(0.3)

browser.find_element_by_name('userName').click()
time.sleep(0.3)

browser.find_element_by_id('password').click()
time.sleep(0.3)

password = browser.find_element_by_id('password')
password.send_keys(userInfo['employeePassword'])
time.sleep(0.3)

# 点击登录，准备开干
browser.find_element_by_class_name('button').click()
time.sleep(2)

print('进入主页了')

# 点击支付报销
print('点击支付报销')
# browser.find_element_by_id('apDiv218').click()
browser.find_element_by_xpath('//*[@id="router-form"]/div/div/a[text()="支付报销"]').click()
time.sleep(5)

# 修改句柄(避免因为新打开标签而获取不到元素)
browser.switch_to.window(browser.window_handles[1])

# 点击对员工付款
browser.find_element_by_xpath('//*[@id="user_tree_menu_panel-body"]/div/div/table/tbody/tr/td/div/span[text('
                              ')="其他费用申请-对员工付款(OEP)"]').click()

time.sleep(2)
print('其他费用申请-对员工付款(OEP)')

print('-->切换iframe')
browser.switch_to.frame(browser.find_element_by_id('tab_8-frame'))
time.sleep(0.3)
print('------------------准备填写票据信息----------------')

# 发票列表
receiptList = []

# 获取要报销的月份(目前只支持一个月)
reimbursementMonth = publicInfo['reimbursementMonth']

cookies = browser.get_cookies()
# 获取cookie中的JSESSIONID
cookieItemId = ''
for cookie in cookies:
    if cookie['name'] == 'JSESSIONID':
        cookieItemId = cookie['name'] + '=' + cookie['value']

print(cookieItemId)
headers = {
    'Cookie': cookieItemId
}
# 执行次数
executeTimes = 0
# 判断是否会获取到数据，如果获取不到，一直执行
notGetData = True
print('------------------获取票据列表中----------------')
while notGetData:
    time.sleep(0.5)
    executeTimes += 1
    print('获取发票列表数据执行第:\t' + str(executeTimes) + '次')
    try:
        # 获取发票信息接口的URL
        postInvoiceListUrl = 'https://sse.chinasoftinc.com:18090/SSE/walletCostConf/postInvoiceList.do?'
        response = requests.post(url=postInvoiceListUrl, data={}, json=None, headers=headers)
        print('查询报销列表结果为:\t')
        print(response.content)
        for invoiceItem in json.loads(response.text)['list']:
            invoiceDate = invoiceItem['invoiceDate']
            if invoiceDate[0:-2] == reimbursementMonth:
                print(invoiceItem)
                receipt = Receipt(receiptTypeMap[invoiceItem['invoiceTypeCode']], invoiceItem['invoiceCode'],
                                  invoiceItem['invoiceNo'],
                                  str(int(invoiceItem['totalAmount'])), invoiceDate, invoiceItem['startDate'],
                                  invoiceItem['endDate'])
                receiptList.append(receipt)
    except JSONDecodeError:
        notGetData = True
    else:
        notGetData = False

# 发票票据张数
receiptCount = len(receiptList)
browser.find_element_by_id('_receiptCount-inputEl').click()
print('发票张数:' + str(len(receiptList)))
time.sleep(0.5)
browser.find_element_by_id('_receiptCount-inputEl').send_keys(receiptCount)
time.sleep(0.5)

print('票据张数 填写[完成]')

# 上海中软华腾软件系统有限公司
benComName = browser.find_element_by_id('head_form_panel_benComName-inputEl')
benComName.send_keys(publicInfo['companyName'])
time.sleep(0.5)
print('受益公司 填写[完成]')

# 项目编码
browser.find_element_by_id('_oep_add_commonForm_basicForm_projectCode-inputEl').click()
projectCode = browser.find_element_by_id('_oep_add_commonForm_basicForm_projectCode-inputEl')
projectCode.send_keys(publicInfo['projectCode'])
time.sleep(0.5)
print('项目编号 填写[完成]')
notGetProjectCodeLi = True
executeProjectCodeTimes = 0
while notGetProjectCodeLi:
    try:
        executeProjectCodeTimes += 1
        print('当前获取项目编号对应的li,第' + str(executeProjectCodeTimes) + '次')
        browser.find_element_by_id('_oep_add_commonForm_basicForm_projectCode-trigger-picker').click()
        time.sleep(1)
        browser.find_element_by_xpath('/html/body/div/div/ul/li[text()="P202104000019"]').click()
        time.sleep(1)
    except ElementNotInteractableException:
        notGetProjectCodeLi = True
    except ElementClickInterceptedException:
        notGetProjectCodeLi = True
    except WebDriverException:
        notGetProjectCodeLi = True
    else:
        notGetProjectCodeLi = False

# 设置支付目的
browser.find_element_by_id('_oep_add_commonForm_basicForm_payPurpose-inputEl').click()
browser.find_element_by_id('_oep_add_commonForm_basicForm_payPurpose-inputEl').send_keys(userInfo['payPurpose'])
time.sleep(1)
print('支付目的[完成]')
# print('------------------准备开始添加票据----------------')

# 关闭选择发票弹出框后点击"添加"，添加报销发票栏
time.sleep(10)
for receiptClickItem in range(len(receiptList)):
    time.sleep(0.3)
    browser.find_element_by_id('costItemAdd').click()

# 获取需要自动填写发票的html块
costItemDivList = browser.find_elements_by_css_selector('#_costItemMainForm0-formWrap > div.x-panel-default')
# receiptList索引值
receiptListIndex = 0

# 反转发票列表
receiptList.reverse()
for itemDivIndex in costItemDivList:
    formItem = itemDivIndex.find_elements_by_css_selector('div.x-form-item-default')
    if len(formItem) > 0:
        # 费用类型
        formItemIdNo = formItem[0].get_attribute('id')[-4:]

        # 去掉费用类型的readonly属性
        expenseTypeRemoveAttrJs = 'document.getElementById("sselocalcombobox-' + formItemIdNo + '-inputEl").removeAttribute("readonly")'
        browser.execute_script(expenseTypeRemoveAttrJs)
        browser.find_element_by_id('sselocalcombobox-' + formItemIdNo + '-inputEl').send_keys('市内交通费-出租车/公交车/地铁/网约车等')

        # 需要等页面渲染完毕
        # 关闭费用类型消息提示框
        time.sleep(0.7)

        # 发票币种 不需要修改

        # 发票类型 增值税专用发票
        formItemIdNo3 = formItem[2].get_attribute('id')[-4:]
        invoiceTypeRemoveAttrJs = 'document.getElementById("sselocalcombobox-' + formItemIdNo3 + '-inputEl").removeAttribute("readonly")'
        browser.execute_script(invoiceTypeRemoveAttrJs)
        browser.find_element_by_id('sselocalcombobox-' + formItemIdNo3 + '-inputEl').send_keys('0')
        time.sleep(0.8)
        # browser.find_element_by_xpath('//*[@id="boundlist-1196-listEl"]/li[text()="增值税专用发票"]').click()

        # 发票金额
        formItemIdNo4 = formItem[3].get_attribute('id')[-4:]
        browser.find_element_by_id('numberfield-' + formItemIdNo4 + '-inputEl').click()
        receiptObj = receiptList.pop()
        browser.find_element_by_id('numberfield-' + formItemIdNo4 + '-inputEl').send_keys(
            str(int(receiptObj.receiptAmount)))

        # 报销金额
        formItemIdNo5 = formItem[4].get_attribute('id')[-4:]
        browser.find_element_by_id('numberfield-' + formItemIdNo5 + '-inputEl').click()
        browser.find_element_by_id('numberfield-' + formItemIdNo5 + '-inputEl').send_keys(receiptObj.receiptAmount)

        # 税率
        formItemIdNo6 = formItem[5].get_attribute('id')[-4:]

        taxRateRemoveAttrJs = 'document.getElementById("sselocalcombobox-' + formItemIdNo6 + '-inputEl").removeAttribute("readonly")'
        browser.execute_script(taxRateRemoveAttrJs)
        browser.find_element_by_id('sselocalcombobox-' + formItemIdNo6 + '-inputEl').send_keys('0')

        # 详细描述(未对周末加班做处理)
        # >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
        # 'world hello world'
        detailDescFormat = publicInfo['detailDescFormat']
        employeeName = userInfo['employeeName']
        employEmail = userInfo['employEmail']
        employPhoneNum = userInfo['employPhoneNum']
        departure = userInfo['departure']
        destination = userInfo['destination']
        detailDescInfo = detailDescFormat.format(receiptObj.startDate, receiptObj.endDate,
                                                 departure, destination, employeeName, employEmail,
                                                 employPhoneNum)

        formItemIdNo12 = formItem[11].get_attribute('id')[-4:]
        browser.find_element_by_id('textfield-' + formItemIdNo12 + '-inputEl').click()
        browser.find_element_by_id('textfield-' + formItemIdNo12 + '-inputEl').send_keys(detailDescInfo)

        # 选择发票 button-1109
        # formItemIdNo14 = int(formItem[11].get_attribute('id')[-4:]) + 2
        # browser.find_element_by_id('button-' + str(formItemIdNo14)).click()

print('------------------添加票据完成----------------')

print('选择审核人（直接主管/项目经理可按工号或者姓名搜索查询选择）')

# browser.find_element_by_id('directLeader_lob_number-inputEl').click()
#
# browser.find_element_by_id('directLeader_lob_number-inputEl').send_keys(publicInfo['directLeaderLobName'])
# print(publicInfo['directLeaderLobNumber'])

# try:
#     # browser.find_element_by_xpath('/div/div/ul/li[text()="' + publicInfo['directLeaderLobName'] + '"]').click()
# except NoSuchElementException:
#     pass

print('直接主管/项目经理[完成]')
browser.find_element_by_id('fin_lob_number-inputEl').click()
browser.find_element_by_id('fin_lob_number-inputEl').send_keys(publicInfo['finLobNumber'])
try:
    browser.find_element_by_xpath('/html/body/div/div/ul/li[text()="' + publicInfo['finLobName'] + '"]').click()
except NoSuchElementException:
    pass
print('财务专员[完成]')

# browser.close()
# 如果票据张数有问题，则再处理
# 发票票据张数
tempReceiptCountObj = browser.find_element_by_id('_receiptCount-inputEl')
tempReceiptCount = tempReceiptCountObj.text
if tempReceiptCount != receiptCount:
    print(tempReceiptCount)
    print(len(receiptList))
    print('需要再处理一下发票张数')
    tempReceiptCountRemoveAttrJs = 'document.getElementById("_receiptCount-inputEl").removeAttribute("readonly")'
    browser.execute_script(tempReceiptCountRemoveAttrJs)
    tempReceiptCountObj.click()
    print(receiptCount)
    tempReceiptCountObj.send_keys(receiptCount)
    tempReceiptCountAddAttrJs = 'document.getElementById("_receiptCount-inputEl").setAttribute("readonly","true")'
    browser.execute_script(tempReceiptCountAddAttrJs)

